import {
  createRouter,
  createWebHashHistory,
} from 'vue-router';

import Layout from '../components/Layout.vue';

const routes = [{
        path: '/login',
        component: () =>
            import ('../views/Login.vue'),
        meta: { title: '登录' },
        hidden: true
    },
    {
        path: '/',
        component: Layout,
        meta: { title: '首页' },
        redirect: '/home',
        hidden: true,
        children: [{
            path: 'home',
            component: () =>
                import ('../views/Home.vue'),
            meta: { title: '首页' }
        }]
    },
    {
        path: '/teacher',
        component: Layout,
        meta: { title: '讲师管理', icon: 'UserFilled' },
        redirect: '/teacher/list',
        children: [{
                path: 'list',
                component: () =>
                    import ('../views/teacher/list.vue'),
                meta: { title: '讲师列表' }
            },
            {
                path: 'create',
                component: () =>
                    import ('../views/teacher/form.vue'),
                meta: { title: '添加讲师' }
            }
        ]
    },
    {
        path: '/course',
        component: Layout,
        redirect: '/course/list',
        meta: { title: '课程管理', icon: 'Platform' },
        children: [{
                path: 'list',
                component: () =>
                    import ('../views/course/list.vue'),
                meta: { title: '课程列表' }
            },
            {
                path: 'create',
                component: () =>
                    import ('../views/course/form.vue'),
                meta: { title: '添加讲师' }
            }
        ]
    }
]

// 通过createRouter创建路由
const router = createRouter({
    history: createWebHashHistory(), // history模式
    routes
})

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
    // 如果请求的是登录页面，就放行。否则判断用户是否登录，如果没有登录就跳转至登录页面
    if (to.path === '/login') {
        next()
    } else {
        // 判断用户是否登录（检查localStorage中是否有token）
        const token = localStorage.getItem('member_token')
        if (token) {
            next()
        } else {
            next('/login')
        }
    }
})

export default router